package util;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;

public class JPAUtil {

    public static EntityManagerFactory factory;

    public static EntityManagerFactory retornarFabrica() {
        if (factory == null) {
            factory = Persistence.createEntityManagerFactory("Sistema_Recibos");
        }
        return factory;
    }

    public static void persistirObjeto(Object obj) {
        EntityManager em = retornarFabrica().createEntityManager();
        EntityTransaction tx = em.getTransaction();
        tx.begin();
        em.merge(obj);
        tx.commit();
        em.close();
    }

    public static Object mergeObjeto(Object obj) {
        EntityManager em = retornarFabrica().createEntityManager();
        EntityTransaction tx = em.getTransaction();
        tx.begin();
        obj = em.merge(obj);
        tx.commit();
        em.close();
        return obj;
                
    }

    public static void delete(Object obj) {
        EntityManager em = retornarFabrica().createEntityManager();
        EntityTransaction tx = em.getTransaction();
        tx.begin();
        obj = em.merge(obj);
        em.remove(obj);
        tx.commit();
        em.close();
    }
}